const vue = new Vue({
    el: "#app",
    data: {
        message: "我的购物车",
        books: [
            {
                id: 0,
                name: "算法导论",
                price: 59.40,
                date: '2021-01-03',
                count: 1
            },{
                id: 1,
                name: "数据结构",
                price: 76.00,
                date: '2021-01-04',
                count: 1
            },{
                id: 2,
                name: "高等数学",
                price: 69.50,
                date: '2021-01-05',
                count: 1
            },{
                id: 3,
                name: "线性代数",
                price: 80.40,
                date: '2021-01-06',
                count: 1
            }
        ]
    },
    computed: {
      getTatalPrice() {
          let totalPrice = 0;
          /*for (let item of this.books) {
              totalPrice += item.price * item.count;
          }*/
          totalPrice = this.books.reduce((preValue, n) => preValue + n.price * n.count, 0);
          /*totalPrice = this.books.reduce(function (pre,book) {
                return pre + book.price*book.count
          },0);*/
          return totalPrice;
      }  
    },
    methods: {
        priceDisplay(price) {
            return "￥" + price.toFixed(2);
        },
        addCount(index) {
            this.books[index].count++;
        },
        subTractCount(index) {
            if(this.books[index].count > 0) {
                this.books[index].count--;
            }
        },
        removeBook(index) {
            // this.books.pop() 移除最后一个
            // this.books.shift() 移除第一个
            this.books.splice(index, 1);
        }
    },
    filters: {
        priceDisplayFilter(price) {
            return "￥" + price.toFixed(2);
        }
    }
});